package demo3;

import java.util.Arrays;
import java.util.Comparator;

class Student2 implements Comparable<Student2>{
    public String name;
    public int age;

    public Student2(String name, int age) {
        this.name=name;
        this.age=age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    public int compareTo(Student2 o) {
        return this.age-o.age;
    }
}

//优点  对类的侵入性 不强
class AgeComparator implements Comparator<Student2> {

    @Override
    public int compare(Student2 o1, Student2 o2) {
        return o1.age-o2.age;
    }
}

class NameComparator implements Comparator<Student2> {

    @Override
    public int compare(Student2 o1, Student2 o2) {
        return o1.name.compareTo(o2.name);
    }
}


public class Test2 {
    public static void main(String[] args) {
        Student2 student1 = new Student2("zhangsan",10);
        Student2 student2 = new Student2("yisi",15);

        AgeComparator age=new AgeComparator();
        System.out.println(age.compare(student1, student2));

        NameComparator name=new NameComparator();
        System.out.println(name.compare(student1, student2));


        Student2[] students = new Student2[4];
        students[0] = new Student2("zhangsan",10);
        students[1] = new Student2("lisi",2);
        students[2] = new Student2("wangmazi",18);
        students[3] = new Student2("liushan",8);

        bubbleSort(students);
        System.out.println(Arrays.toString(students));
    }

    public static void bubbleSort(Comparable[] comparable) {
        for(int i=0; i<comparable.length-1; ++i) {
            for(int j=0; j<comparable.length-1-i; ++j) {
                if(comparable[j].compareTo(comparable[j+1]) > 0) {
                    Comparable tmp = comparable[j];
                    comparable[j] = comparable[j+1];
                    comparable[j+1] = tmp;
                }
            }
        }
    }
}
